<template id="tree-component">
  <style>
    ul.tree {
      list-style-type: none;
      padding-left: 20px;
    }
    li.tree-node {
      position: relative;
      padding-left: 20px;
    }
    li.tree-node::before {
      content: "";
      position: absolute;
      left: 0;
      top: 5px;
      width: 10px;
      height: 10px;
      background-color: #333;
      border-radius: 50%;
    }
    .tree {
      padding-left: 10px;
    }
    .list-group-item {
      border: none;
      padding: 5px 10px;
    }
  </style>
  <ul class="tree list-group" id="treeRoot"></ul>
</template>

<script>
  class TreeComponent extends HTMLElement {
    constructor() {
      super();
      const template = document.getElementById('tree-component');
      const shadowRoot = this.attachShadow({ mode: 'open' });
      shadowRoot.appendChild(template.content.cloneNode(true));
    }

    connectedCallback() {
      // 初始化时可选地调用 renderTree 方法
      const data = this._data || [];
      this.renderTree(data);
    }

    // 提供一个方法用于外部传入数据并渲染树
    renderTree(data) {
      this._data = data;
      const container = this.shadowRoot.getElementById('treeRoot');
      container.innerHTML = ''; // 清空原有内容

      function buildSubTree(parent, nodes) {
        const ul = document.createElement('ul');
        nodes.forEach(node => {
          const li = document.createElement('li');
          li.className = 'tree-node list-group-item';
          li.textContent = node.name;
          ul.appendChild(li);

          if (node.children && node.children.length > 0) {
            buildSubTree(li, node.children);
          }
        });
        parent.appendChild(ul);
      }

      if (data && data.length) {
        buildSubTree(container, data);
      }
    }
  }

  customElements.define('tree-component', TreeComponent);
</script>